package com.example.translateappjava.Activity.MineFragmentActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.translateappjava.DataBase.UserDbHelper;
import com.example.translateappjava.DataBase.UserInfo;
import com.example.translateappjava.R;
import com.example.translateappjava.Singleton.GlobalData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PersonActivity extends AppCompatActivity {
    private ProgressBar progressBar;
    private EditText perName, perBirthday, perHeight, perWeight, perGender, perEmail, perPhoneNo, perSportLevel;
    private ImageView imageView;
    private final int totalFields = 8; // 总共的字段数
    private static final String TAG_BACKEND_UPDATE = "BackendUpdate"; // 用于后端请求的日志TAG
    private static final String API_USER_INFO_URL = GlobalData.getInstance().getBaseUrl() + "/user/userinfo";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_person);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        ImageView iv_bir = findViewById(R.id.qst_birthday);
        ImageView iv_spo = findViewById(R.id.qst_sportLevel);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ImageButton btn_save = findViewById(R.id.btn_save);
        @SuppressLint({"MissingInflatedId", "LocalSuppress"}) ImageButton btn_leave = findViewById(R.id.btn_leave);

        imageView = findViewById(R.id.profile_image);
        perName = findViewById(R.id.per_name);
        perBirthday = findViewById(R.id.per_birthday);
        perHeight = findViewById(R.id.per_height);
        perWeight = findViewById(R.id.per_weight);
        perGender = findViewById(R.id.per_gender);
        perEmail = findViewById(R.id.per_email);
        perPhoneNo = findViewById(R.id.per_phoneNo);
        perSportLevel = findViewById(R.id.per_sportLevel);
        progressBar = findViewById(R.id.progressBar);

        /**
         * 提供照片点击监听
         */
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(PersonActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    // 请求权限
                    ActivityCompat.requestPermissions(PersonActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            100);
                } else {
                    // 权限已授予，继续操作
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 100);
                    Toast.makeText(getApplicationContext(),"请稍等", Toast.LENGTH_SHORT);
                }

            }
        });
        /**
         * 设置点击后的事件
         */

        iv_bir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(PersonActivity.this)
                        .setMessage("2003-03-08")
                        .setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setTitle("示例：")
                        .show();
            }
        });

        iv_spo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(PersonActivity.this)
                        .setMessage( "请从1-5等级中找到你的等级\n" +
                                "🧑‍🦽  1 久坐（很少运动）\n" +
                                "🚵‍♂️ 2  轻度活动（每周运动1-3天）\n" +
                                "🏃 3  中度活动（每周运动3-5天）\n" +
                                "🤺 4  重度活动（每周运动6-7天）\n" +
                                "🏋️ 5  极重度活动（每天运动或体力劳动）")
                        .setPositiveButton("我知道啦", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .setTitle("温馨提醒")
                        .show();
            }
        });
        // 假设userInfo是从数据库或其他地方获取的当前登录用户的信息
        UserInfo currentUserInfo = UserInfo.getsUserInfo();
        if (currentUserInfo != null) {
            // 使用当前用户信息来填充表单字段
            perName.setText(currentUserInfo.getName());
            perBirthday.setText(currentUserInfo.getBirth());
            perHeight.setText(currentUserInfo.getHeight());
            perWeight.setText(currentUserInfo.getWeight());
            perGender.setText(currentUserInfo.getSex());
            perEmail.setText(currentUserInfo.getEmail());
            perPhoneNo.setText(currentUserInfo.getPhoneNumber());
            perSportLevel.setText(currentUserInfo.getSportLevel());
            if (UserInfo.getsUserInfo().getImage() != null)
            {
                Bitmap bitmap = BitmapFactory.decodeByteArray(UserInfo.sUserInfo.getImage(), 0,UserInfo.sUserInfo.getImage().length);
                // 设置 Bitmap 到 ImageView
                imageView.setImageBitmap(bitmap);
            }
        }

        // 设置文本监听器来更新进度条
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateProgressBar();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };

        // 为每个表单字段添加文本监听器
        perName.addTextChangedListener(textWatcher);
        perBirthday.addTextChangedListener(textWatcher);
        perHeight.addTextChangedListener(textWatcher);
        perWeight.addTextChangedListener(textWatcher);
        perGender.addTextChangedListener(textWatcher);
        perEmail.addTextChangedListener(textWatcher);
        perPhoneNo.addTextChangedListener(textWatcher);
        perSportLevel.addTextChangedListener(textWatcher);

        // 更新进度条
        updateProgressBar();


        btn_leave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmAndExit();
            }
        });

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUserInfo();
            }
        });

    }

        private void confirmAndExit () {
            new AlertDialog.Builder(this)
                    .setMessage("确定要退出编辑吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Exit the activity
                            finish();
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }


        private void updateProgressBar () {
            int filledFields = 0;
            if (!perName.getText().toString().trim().isEmpty()) filledFields++;
            if (!perBirthday.getText().toString().trim().isEmpty()) filledFields++;
            if (!perHeight.getText().toString().trim().isEmpty()) filledFields++;
            if (!perWeight.getText().toString().trim().isEmpty()) filledFields++;
            if (!perGender.getText().toString().trim().isEmpty()) filledFields++;
            if (!perEmail.getText().toString().trim().isEmpty()) filledFields++;
            if (!perPhoneNo.getText().toString().trim().isEmpty()) filledFields++;
            if (!perSportLevel.getText().toString().trim().isEmpty()) filledFields++;

            int progress = (int) ((filledFields / (float) totalFields) * 100);
            progressBar.setProgress(progress);
        }
        private void saveUserInfo () {
            if (!validateInput()) {
                return;
            }
            // Get the user input data
            String newName = perName.getText().toString();
            String newBirth = perBirthday.getText().toString();
            String newHeight = perHeight.getText().toString();
            String newWeight = perWeight.getText().toString();
            String newGender = perGender.getText().toString();
            String newEmail = perEmail.getText().toString();
            String newPhoneNo = perPhoneNo.getText().toString();
            String newSportLevel = perSportLevel.getText().toString();

            // Update the UserInfo instance
            UserInfo currentUserInfo = UserInfo.getsUserInfo();
            if (currentUserInfo != null) {
                currentUserInfo.setName(newName);
                currentUserInfo.setBirth(newBirth); // 确保 newBirth 是 "YYYY-MM-DD" 格式
                currentUserInfo.setHeight(newHeight);
                currentUserInfo.setWeight(newWeight);
                currentUserInfo.setSex(newGender);
                currentUserInfo.setEmail(newEmail);
                currentUserInfo.setPhoneNumber(newPhoneNo);
                currentUserInfo.setSportLevel(newSportLevel);

                UserDbHelper dbHelper = UserDbHelper.getInstance(PersonActivity.this);
                dbHelper.updateUserInfo(currentUserInfo);
                Log.d("UserID调试", "当前用户ID: " + UserInfo.getsUserInfo().getUsername());
                // 通知用户本地信息已更新
//                Toast.makeText(PersonActivity.this, "个人信息已在本地更新", Toast.LENGTH_SHORT).show();

                OkHttpClient client = new OkHttpClient();
                MediaType JSON_TYPE = MediaType.get("application/json; charset=utf-8");

                JSONObject jsonRequestBody = new JSONObject();
                try {
                    jsonRequestBody.put("userName", UserInfo.getsUserInfo().getUsername());
                    jsonRequestBody.put("trueName", newName);
                    jsonRequestBody.put("gender", newGender);
                    jsonRequestBody.put("birthDay", newBirth); // 再次强调：确保 newBirth 是 "YYYY-MM-DD" 格式的字符串
                    jsonRequestBody.put("type", 1); // 根据你的规范
                    jsonRequestBody.put("email", newEmail);
                    jsonRequestBody.put("height", String.valueOf(newHeight)); // 后端需要字符串
                    jsonRequestBody.put("weight", String.valueOf(newWeight)); // 后端需要字符串
                    jsonRequestBody.put("phoneNumber", newPhoneNo);
                    jsonRequestBody.put("sportLevel", String.valueOf(newSportLevel)); // 后端需要字符串

                } catch (JSONException e) {
                    Log.e(TAG_BACKEND_UPDATE, "JSONERROR: " + e.getMessage());
                    Toast.makeText(PersonActivity.this, "JSONERROR", Toast.LENGTH_SHORT).show();
                }

                if (jsonRequestBody.length() > 0) {
                    RequestBody requestBody = RequestBody.create(jsonRequestBody.toString(), JSON_TYPE);
                    Request request = new Request.Builder()
                            .url(API_USER_INFO_URL)
                            .post(requestBody)
                            .build();

                    Log.d(TAG_BACKEND_UPDATE, "POST: " + API_USER_INFO_URL);
                    Log.d(TAG_BACKEND_UPDATE, "raw: " + jsonRequestBody.toString());

                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e(TAG_BACKEND_UPDATE, "后端更新请求连接失败: " + e.getMessage(), e);
                            runOnUiThread(() -> Toast.makeText(PersonActivity.this, "同步到服务器失败: " + e.getMessage(), Toast.LENGTH_LONG).show());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            final String responseBodyString = response.body().string(); // 重要：只能调用一次
                            Log.d(TAG_BACKEND_UPDATE, "Response: " + responseBodyString);

                            if (!response.isSuccessful()) {
                                Log.e(TAG_BACKEND_UPDATE, "requestERROR. HTTPcode: " + response.code());
                                runOnUiThread(() -> Toast.makeText(PersonActivity.this, "ServerERROR，code: " + response.code(), Toast.LENGTH_LONG).show());
                                return;
                            }

                            try {
                                JSONObject jsonResponse = new JSONObject(responseBodyString);
                                int code = jsonResponse.optInt("code", -1);
                                String msg = jsonResponse.optString("msg", "unknown response");

                                if (code == 200) {
                                    Log.i(TAG_BACKEND_UPDATE, "Update success: " + msg);
                                    runOnUiThread(() -> Toast.makeText(PersonActivity.this, "个人信息已同步", Toast.LENGTH_SHORT).show());
                                } else {
                                    Log.e(TAG_BACKEND_UPDATE, "ERROR. code: " + code + ", msg: " + msg);
                                    final String errorMsg = msg;
                                    runOnUiThread(() -> Toast.makeText(PersonActivity.this, "ServerEROR: " + errorMsg + " (code:" + code + ")", Toast.LENGTH_LONG).show());
                                }
                            } catch (JSONException e) {
                                Log.e(TAG_BACKEND_UPDATE, "ResponseJSONERROR: " + e.getMessage(), e);
                                runOnUiThread(() -> Toast.makeText(PersonActivity.this, "解析服务器响应失败", Toast.LENGTH_LONG).show());
                            }
                        }
                    });
                }
            }
        }


        private boolean validateInput () {
            // 验证姓名，假设只允许字母和空格
            if (!perName.getText().toString().matches("^[\\u4e00-\\u9fa5a-zA-Z]+$")) {
                perName.setError("姓名必须为非空的中文或英文字符");
                return false;
            }

            // 验证生日，假设格式为YYYY-MM-DD
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false); // 设置为严格解析日期
            try {
                Date date = sdf.parse(perBirthday.getText().toString());
                // 如果能够解析，则日期有效
            } catch (ParseException e) {
                perBirthday.setError("生日格式不正确，正确格式为: YYYY-MM-DD\n" +
                        "确保您的生日是人类社会中存在的一天");
                return false;
            }


            // 验证身高，假设身高范围为30cm到260cm
            String heightStr = perHeight.getText().toString();
            if (!heightStr.matches("^\\d+(\\.\\d+)?$")) {
                perHeight.setError("身高必须为数字");
                return false;
            } else {
                float height = Float.parseFloat(heightStr);
                if (height < 30 || height > 260) {
                    perHeight.setError("身高必须在30cm到260cm之间");
                    return false;
                }
            }

            // 验证体重，假设体重范围为40kg到120kg
            String weightStr = perWeight.getText().toString();
            if (!weightStr.matches("^\\d+(\\.\\d+)?$")) {
                perWeight.setError("体重必须为数字");
                return false;
            } else {
                float weight = Float.parseFloat(weightStr);
                if (weight < 20 || weight > 220) {
                    perWeight.setError("体重必须在20kg到220kg之间");
                    return false;
                }
            }

            // 验证性别，假设只允许"男"或"女"
            if (!perGender.getText().toString().matches("男|女")) {
                perGender.setError("性别输入不正确，请输入'男'或'女'");
                return false;
            }

            // 验证电子邮件，使用常见的电子邮件正则表达式
            if (!perEmail.getText().toString().matches("[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\\.+[a-z]+")) {
                perEmail.setError("电子邮件格式不正确");
                return false;
            }

            // 验证电话号码，假设为10到13位数字
            if (!perPhoneNo.getText().toString().matches("^\\d{10,13}$")) {
                perPhoneNo.setError("电话号码格式不正确");
                return false;
            }

            // 验证运动水平，假设只允许1到5的数字
            if (!perSportLevel.getText().toString().matches("^[1-5]$")) {
                perSportLevel.setError("运动水平必须为1到5的数字");
                return false;
            }

            return true;
        }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);



        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            imageView.setImageURI(imageUri);
            try {
                Bitmap bitmap = ImageDecoder.decodeBitmap(
                        ImageDecoder.createSource(this.getContentResolver(), imageUri)
                );
                byte[] imageBytes = getBitmapAsByteArray(bitmap);
                UserInfo currentUserInfo = UserInfo.getsUserInfo();
                currentUserInfo.setImage(imageBytes);
                UserDbHelper dbHelper = UserDbHelper.getInstance(PersonActivity.this);
                dbHelper.updateUserInfo(currentUserInfo);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
    }//

    private byte[] getBitmapAsByteArray(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
        return outputStream.toByteArray();
    }


    }

